package com.yuanwushe.blue.thread;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;

import com.yuanwushe.blue.model.VideoItem;

import java.util.concurrent.locks.Condition;

/**
 * Created by blue on 2018/5/20.
 */

public class VideoThread extends AsyncTask<Object, VideoItem, Void>
{
    public Context context;
    public IThread iThread;

    public VideoThread(Context context, IThread<VideoItem> iThread)
    {
        this.context = context;
        this.iThread = iThread;
    }
    @Override
    protected Void doInBackground(Object... objects) {
        Uri url = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

        String[] searchKey = new String[]{
                MediaStore.Video.Media.TITLE,
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_ADDED
        };
//        String[] keywords = null;
        String where = MediaStore.Video.Media.DATA + " like \"%/Video+%\"";
//        String where = MediaStore.Video.Media.DATA;
        String sortOrder = MediaStore.Video.Media.DEFAULT_SORT_ORDER;

        ContentResolver contentResolver = context.getContentResolver();
        Cursor cursor = contentResolver.query(url, searchKey, null, null, null);
        if (cursor != null)
        {
            while (cursor.moveToNext() && !isCancelled())
            {
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
                String name = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
                String careatedTime = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED));

                VideoItem videoItem = new VideoItem(name, path, careatedTime);

                this.onProgressUpdate(videoItem);
            }

            cursor.close();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(VideoItem... values) {
        VideoItem item = values[0];
        iThread.success(item);
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        iThread.cancel();
        super.onPostExecute(aVoid);
    }

    @Override
    protected void onCancelled() {
        iThread.cancel();
        super.onCancelled();
    }
}
